#include "filereceiver.h"

TcpServer::TcpServer(QObject *parent)
    : QTcpServer(parent)
{
}

TcpServer *TcpServer::getInstance()
{
    static TcpServer *instance = 0;

    if(!instance)
        instance = new TcpServer();

    return instance;
}

void TcpServer::incomingConnection(int handle)
{
    FileReceiver *fileReceiver = new FileReceiver(this);
    fileReceiver->setSocketDescriptor(handle);
}

FileReceiver::FileReceiver(QObject *parent)
    : QTcpSocket(parent)
{
    nextBlockSize = 0;
    connect(this, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
}

void FileReceiver::processReadyRead()
{
    QDataStream in(this);

    forever {
        if(nextBlockSize == 0)
        {
            if(QTcpSocket::bytesAvailable() < sizeof(quint64))
            {
                return;
            }

            in >> nextBlockSize;
        }

        if(QTcpSocket::bytesAvailable() < nextBlockSize)
        {
            return;
        }

        QString fileName;
        in >> fileName;
        QFile file(fileName);

        if(!file.open(QFile::WriteOnly)) {
            QByteArray temp;
            in >> temp;
            nextBlockSize = 0;
            continue;
        }

        QByteArray temp;
        in >> temp;
        file.write(temp);
        file.close();
        nextBlockSize = 0;

        qDebug() << temp.size();

        QFileInfo fileInfo(file);
        emit fileReceived(fileInfo.absoluteFilePath());
        QTcpSocket::disconnectFromHost();
        connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));
    }
}
